﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Matrix.Framework.MessageBus.Net;

namespace Lootom.Nms.WindowsService
{
    public class MessageBusService
    {
        private readonly byte[] _buff = new byte[1024*10];
        private readonly ServerMessageBus _smb;
        private readonly TcpListener _tcpListener;

        public MessageBusService()
        {
            _smb = new ServerMessageBus("123", 1234, null);
            _tcpListener = new TcpListener(IPAddress.Any, 23);
            _tcpListener.Start();
            var thread = new Thread(AcceptTcpClient);
            thread.Start();
        }

        /// <summary>
        /// 接受Telnet请求
        /// </summary>
        private void AcceptTcpClient()
        {
            TcpClient tcpClient = _tcpListener.AcceptTcpClient();
            NetworkStream clientStream = tcpClient.GetStream();
            clientStream.BeginRead(_buff, 0, _buff.Length, Callback, clientStream);
            AcceptTcpClient();
        }

        private void Callback(IAsyncResult asyncResult)
        {
            var ns = (NetworkStream) asyncResult.AsyncState;
            int n = ns.EndRead(asyncResult);
            if (n > 0)
            {
                ns.Write(_buff, 0, n);
                ns.BeginRead(_buff, 0, _buff.Length, Callback, ns);
            }
        }
    }
}